package com.coocaa.ops.common.tool.exception;

import com.alibaba.fastjson.JSON;
import com.coocaa.ops.common.tool.http.HttpCodeEnums;
import lombok.Getter;
import lombok.Setter;
import org.springframework.ui.ModelMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @author tangminghong
 * @date 2020-06-10 17:38
 */
public class BusinessException extends BaseException {

    /**
     * 导致异常的数据
     */
    @Setter
    @Getter
    private Map<String, Object> errOpData;

    /**
     * 异常信息
     */
    @Setter
    @Getter
    private String errMsg;

    /**
     * @param errOpData
     * @param errMsg
     */
    public BusinessException(Map<String, Object> errOpData, String errMsg) {
        this.errOpData = errOpData;
        this.errMsg = errMsg;
    }

    public BusinessException() {
    }

    public BusinessException(Throwable ex) {
        super(ex);
        this.errOpData = new HashMap<>();
    }

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(String message, Throwable ex) {
        super(message, ex);
    }

    @Override
    public void handler(ModelMap modelMap) {
        modelMap.put("code", this.getCode().value());
        modelMap.put("msg", getErrInfoStringBuilder().toString());
        modelMap.put("timestamp", System.currentTimeMillis());
    }

    @Override
    public HttpCodeEnums getCode() {
        return HttpCodeEnums.INTERNAL_SERVER_ERROR;
    }

    /**
     * 封装异常信息
     *
     * @return
     */
    public StringBuilder getErrInfoStringBuilder() {
        StringBuilder stringBuilder = new StringBuilder(100);
        stringBuilder.append("异常参数摘要:")
                .append(JSON.toJSONString(this.getErrOpData()))
                .append(",异常信息:")
                .append(this.getErrMsg());
        return stringBuilder;
    }
}
